package unicall.em.services;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import unicall.em.dtos.SipAccountDto;
import unicall.em.models.SipAccount;
import unicall.em.repositories.SipAccountRepository;
import unicall.em.utils.HttpClientUtil;

@Service
public class SipAccountServiceImpl implements SipAccountService{

    @Autowired
    private SipAccountRepository repository;
    
    @Override
    public void add(SipAccountDto dto) {
       SipAccount account = new SipAccount();
       account.setTenantId(dto.getTenantId());
       account.setClientNumber(dto.getClientNumber());
       account.setPassword(dto.getPassword());
       account.setAgentId(dto.getAgentId());
       repository.saveAndFlush(account);
    }

    @Override
    public void release(String clientNumber) {
       repository.releaseAccount(clientNumber);
        
    }

    @Override
    public void bind(String clientNumber, String agentId) {
        repository.bind(clientNumber, agentId);
        
    }

    @Override
    public void unbind(String clientNumber) {
       repository.unbind(clientNumber);
    }

    @Override
    public JSONObject apply(String appId) {
        HttpClientUtil util = new HttpClientUtil();
        Map<String,String> params = new HashMap<String,String>();
        params.put("appId", appId);
        JSONObject obj = null;
        try{
            String result = util.doPost(CREATE_URL, params);
            obj = JSONObject.parseObject(result);
        }catch(Exception e){
          
        }
        return obj;
    }
    
    
    public JSONObject release(String appId,String clientNumber) {
        HttpClientUtil util = new HttpClientUtil();
        Map<String,String> params = new HashMap<String,String>();
        params.put("appId", appId);
        params.put("clientNumber", clientNumber);
        JSONObject obj = null;
        try{
            String result = util.doPost(RELEASE_URL, params);
            obj = JSONObject.parseObject(result);
        }catch(Exception e){
          
        }
        return obj;
    }
    
    @Override
    public Page<SipAccount> queryAll(Specification<SipAccount> specation, Pageable pageable) {
        return repository.findAll(specation, pageable);
    }
        
    
    
    

    private final static String CREATE_URL="http://127.0.0.1:9011/sip/create";
    private final static String RELEASE_URL="http://127.0.0.1:9011/sip/destroy";


}

